package com.ias.agdis_r.fragment.main;

import java.util.ArrayList;
import java.util.List;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.message.MessageDetailsActivity;
import com.ias.agdis_r.activity.message.MessageSendActivity;
import com.ias.agdis_r.activity.message.MessageSendDetalisActivity;
import com.ias.agdis_r.adapter.MessageListAdapter;
import com.ias.agdis_r.bean.auth.AuthEnum;
import com.ias.agdis_r.db.MyBeanTempDBHelper;
import com.ias.agdis_r.db.message.MyMessageBean;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.manager.ServiceManage;
import com.ias.agdis_r.netservice.ReceiveMessageThread;
import com.ias.agdis_r.util.S;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
//import android.support.v4.app.ListFragment;
import androidx.fragment.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

/**
 * @author qibo.yu
 * @version 2015年8月14日 上午8:18:41
 **/
public class MessageListFragment extends ListFragment implements AdapterView.OnItemSelectedListener {

    private static final String COLS = "stm,sem,mtn,fln,txt,ack,mti,_id,tgn,fst,readed";
    private static final String ORDER = "ORDER BY stm ASC";
    private static Context context = DataBaseManager.getInstance().getContext();
    private static final String DEFAULT_FLIGHT_FILTER_VAL = context.getString(R.string.flight1);

    /**
     * 界面顶端过滤器
     */
    private Spinner filterReaded, filterFlight, filterReceipt;
    private TextView noMessageInfo;
    private MyBeanTempDBHelper<MyMessageBean> messageDBHelper;
    private SQLiteDatabase database;
    private Cursor cursor;

    private boolean scrollToLast = true;

    private int readedPos = 0, fstPos = 0;
    private String fln = null;

    private ArrayAdapter<Object> flnAdapter;
    private MessageListAdapter messageListAdapter;

    private BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(isVisible()){
                //scrollToLast = false;
            }
            loadData();
        }

    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_message_list, container, false);
        noMessageInfo = (TextView) view.findViewById(R.id.tv_noInfo);
        return view;

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            loadData();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (ServiceManage.getInstance().getIsLogon()) {
            loadData();
        }
        getActivity().registerReceiver(receiver, new IntentFilter(ReceiveMessageThread.ACTION_MESSAGE_ARRIVED));

    }

    @Override
    public void onPause() {
        getActivity().unregisterReceiver(receiver);
        super.onPause();
    }

    private void loadData() {

        String userName = JavaBeanManager.getInstance().getUserinfo().getEnb();

        String flightSql = "SELECT distinct fln FROM " + this.messageDBHelper.getTableName()
                + " where fln is not null and fln != '' and user_name = '" + userName + "'ORDER BY fln ASC";
        refreshFlightFilter(database.rawQuery(flightSql, null));

        StringBuilder sqlBuilder = new StringBuilder("SELECT ").append(COLS).append(" FROM ")
                .append(messageDBHelper.getTableName()).append(" ");
        sqlBuilder.append(" WHERE user_name = '").append(userName).append("' ");

        if (readedPos == 1) {
            sqlBuilder.append(" and readed is not null and readed != '' and readed != '2'");
        } else if (readedPos == 2) {
            sqlBuilder.append(" and (readed is null or readed = '' or readed = '2')");
        }

        if (fstPos == 1) {
            sqlBuilder.append(" and ack = 'Y' and fst != 'Y' ");
        } else if (fstPos == 2) {
            sqlBuilder.append(" and fst = 'Y' ");
        }

        if (S.isNotEmpty(fln) && !DEFAULT_FLIGHT_FILTER_VAL.equals(fln)) {
            sqlBuilder.append(" and fln = '").append(fln).append("' ");
        }

//		if (readedPos != 0 || fstPos != 0 || (S.isNotEmpty(fln) && !DEFAULT_FLIGHT_FILTER_VAL.equals(fln))) {
        if (readedPos != 0) {
            sqlBuilder.append(" and (sem is not null and sem != '') ");
        }

        sqlBuilder.append(ORDER);
        Log.d("C_sql", sqlBuilder.toString());
        cursor = database.rawQuery(sqlBuilder.toString(), null);

        messageListAdapter.changeCursor(cursor);
        if (0 == messageListAdapter.getCount()) {
            noMessageInfo.setVisibility(View.VISIBLE);
        } else {
            noMessageInfo.setVisibility(View.GONE);
        }
        Log.d("C_scroll","val:" + scrollToLast);
        if (scrollToLast) {
            int count = messageListAdapter.getCount();
            if(count> 1){
                getListView().setSelection(count - 1);
            }
        }
        scrollToLast = true;

    }

    private void refreshFlightFilter(Cursor rawQuery) {
        List<String> flns = new ArrayList<String>();
        flns.add(DEFAULT_FLIGHT_FILTER_VAL);
        Log.d("C_cursor", rawQuery.getCount() + ",");
        while (rawQuery.moveToNext()) {
            flns.add(rawQuery.getString(0));
        }
        flnAdapter.clear();
        flnAdapter.addAll(flns);
        this.flnAdapter.notifyDataSetChanged();

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        messageDBHelper = new MyBeanTempDBHelper<MyMessageBean>(getActivity(), MyMessageBean.class);
        database = messageDBHelper.getReadableDatabase();
    }

    @Override
    public void onDestroy() {
        database.close();
        database = null;
        super.onDestroy();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        filterReaded = (Spinner) view.findViewById(R.id.filter_readed);
        filterReceipt = (Spinner) view.findViewById(R.id.filter_task);
        filterFlight = (Spinner) view.findViewById(R.id.filter_flight);

        filterReaded.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item,
                getResources().getStringArray(R.array.filter_readed_values)));
        filterReceipt.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item,
                getResources().getStringArray(R.array.filter_receipt_values)));

        flnAdapter = new ArrayAdapter<Object>(getActivity(), android.R.layout.simple_spinner_dropdown_item);
        filterFlight.setAdapter(flnAdapter);

        messageListAdapter = new MessageListAdapter(getActivity(), cursor, true);
        setListAdapter(messageListAdapter);

        filterReaded.setOnItemSelectedListener(this);
        filterFlight.setOnItemSelectedListener(this);
        filterReceipt.setOnItemSelectedListener(this);

        getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (cursor != null) {
                    cursor.moveToPosition(position);
                    String sem = cursor.getString(1);
                    String tgn = cursor.getString(8);

                    scrollToLast = false;

                    if (S.isNotEmpty(sem)) {
                        Intent intent = new Intent(getActivity(), MessageDetailsActivity.class);
                        intent.putExtra(MessageDetailsActivity.EXTRA_MESSAGE_TGN, tgn);
                        getActivity().startActivity(intent);
                    } else {
                        showMessageFullScreen(cursor.getString(4));
                    }
                }
            }
        });

    }

    protected void showMessageFullScreen(String txt) {
        // final FrameLayout rootView =
        // UiUtil.getActivityRootLayout(getActivity());
        // TextView msgView = (TextView)
        // LayoutInflater.from(getActivity()).inflate(R.layout.view_message_send,
        // rootView,
        // false);
        //
        // msgView.setText(txt);
        // rootView.addView(msgView);
        // msgView.requestFocus();
        // msgView.setOnKeyListener(new TextView.OnKeyListener() {
        //
        // @Override
        // public boolean onKey(View v, int keyCode, KeyEvent event) {
        // Log.d("C_key", keyCode + "" + KeyEvent.KEYCODE_BACK);
        // if (keyCode == KeyEvent.KEYCODE_BACK) {
        // rootView.removeView(v);
        // return true;
        // }
        // return false;
        // }
        // });
        // msgView.setOnClickListener(new View.OnClickListener() {
        //
        // @Override
        // public void onClick(View v) {
        // rootView.removeView(v);
        //
        // }
        // });

        Intent intent = new Intent(getActivity(), MessageSendDetalisActivity.class);
        intent.putExtra(MessageSendDetalisActivity.EXTRA_MESSAGE_TEXT, txt);
        getActivity().startActivity(intent);

    }

    public void initActionBarEvent() {
        View addAction = getActivity().getActionBar().getCustomView().findViewById(R.id.action_add);
        addAction.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_SITUATIONREPORT.toString())) {
                    Intent intent = new Intent(getActivity(), MessageSendActivity.class);
                    intent.putExtra(MessageSendActivity.EXTRA_TYPE, MessageSendActivity.TYPE_NORMAL);
                    getActivity().startActivity(intent);
                } else {
                    EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO, context.getString(R.string.no_AI_T_SITUATIONREPORT), false);
                }

            }
        });
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (ServiceManage.getInstance().getIsLogon()) {
            this.readedPos = filterReaded.getSelectedItemPosition();
            this.fstPos = filterReceipt.getSelectedItemPosition();
            this.fln = (String) filterFlight.getSelectedItem();
            scrollToLast = false;
            loadData();
        }

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        // TODO Auto-generated method stub

    }

}
